<template>
  <div class="layout-container">
    <el-container class="main-container">
      <!-- 左侧菜单（响应式） -->
      <el-aside
        :width="isCollapse ? '64px' : '240px'"
        :class="['sidebar', { 'sidebar-collapse': isCollapse }]"
      >
        <div class="logo-container">
          <h2 v-show="!isCollapse">员工请假系统</h2>
          <h2 v-show="isCollapse" class="logo-text-short">EAS</h2>
        </div>
        <el-menu
          :default-active="activeMenu"
          :collapse="isCollapse"
          :collapse-transition="false"
          class="el-menu-vertical"
          @select="handleMenuSelect"
        >
          <el-menu-item
            v-for="menu in menuList"
            :key="menu.path"
            :index="menu.path"
          >
            <el-icon><component :is="menu.icon" /></el-icon>
            <template #title>{{ menu.name }}</template>
          </el-menu-item>
        </el-menu>
      </el-aside>

      <!-- 右侧内容区 -->
      <el-container>
        <!-- 顶部导航栏 -->
        <el-header class="main-header">
          <div class="header-content">
            <div class="header-left">
              <el-button
                @click="toggleSidebar"
                :icon="isCollapse ? Expand : Fold"
                class="sidebar-toggle-btn"
                circle
              />
              <div class="breadcrumb">
                <h3>{{ currentPageTitle }}</h3>
              </div>
            </div>
            <div class="user-info">
              <el-tag :type="roleTypeMap[userInfo.roleType]?.type" effect="plain">
                {{ roleTypeMap[userInfo.roleType]?.name }}
              </el-tag>
              <span class="username">{{ userInfo.realName || userInfo.phone }}</span>
              <el-dropdown @command="handleCommand">
                <span class="el-dropdown-link">
                  <el-icon><User /></el-icon>
                  <el-icon class="el-icon--right"><ArrowDown /></el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item disabled>
                      <div style="padding: 5px 0; color: #606266;">
                        <div>ID: {{ userInfo.id }}</div>
                        <div v-if="userInfo.position">职位: {{ userInfo.position }}</div>
                      </div>
                    </el-dropdown-item>
                    <el-dropdown-item divided command="logout">
                      <el-icon><SwitchButton /></el-icon>
                      退出登录
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
        </el-header>

        <!-- 主内容区 -->
        <el-main class="main-content">
          <router-view v-slot="{ Component }">
            <transition name="fade" mode="out-in">
              <component :is="Component" />
            </transition>
          </router-view>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User, ArrowDown, SwitchButton, Expand, Fold } from '@element-plus/icons-vue'
import { getUserInfo, removeToken, getRoleName, setUserInfo } from '@/utils/auth'
import { getMenuByRole } from '@/config/menu'
import { getUserInfoApi } from '@/api/user'

const router = useRouter()
const route = useRoute()

// 用户信息
const userInfo = ref({
  id: null,
  roleType: null,
  realName: '',
  phone: '',
  position: '',
  deptId: null
})

// 菜单列表
const menuList = ref([])

// 侧边栏折叠状态
const isCollapse = ref(false)

// 当前激活的菜单
const activeMenu = computed(() => route.path)

// 当前页面标题
const currentPageTitle = computed(() => {
  const menu = menuList.value.find(m => m.path === route.path)
  return menu ? menu.meta.title : '首页'
})

// 角色类型映射
const roleTypeMap = {
  1: { name: '普通员工', type: 'success' },
  2: { name: '部门经理', type: 'warning' },
  3: { name: '系统管理员', type: 'danger' }
}

// 切换侧边栏
const toggleSidebar = () => {
  isCollapse.value = !isCollapse.value
  // 保存状态到localStorage
  localStorage.setItem('sidebar_collapsed', isCollapse.value)
}

// 加载用户完整信息
const loadUserInfo = async () => {
  try {
    const res = await getUserInfoApi()
    if (res.data) {
      // 更新用户信息
      userInfo.value = {
        id: res.data.id,
        roleType: res.data.roleType,
        realName: res.data.realName || '未设置',
        phone: res.data.phone,
        position: res.data.position || '未设置',
        deptId: res.data.deptId,
        email: res.data.email,
        status: res.data.status
      }
      // 保存到本地存储
      setUserInfo(userInfo.value)
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    // 如果获取失败，使用 token 中的基本信息
    const basicInfo = getUserInfo()
    if (basicInfo) {
      userInfo.value = basicInfo
    }
  }
}

// 初始化用户信息和菜单
onMounted(async () => {
  // 从localStorage恢复侧边栏状态
  const savedCollapseState = localStorage.getItem('sidebar_collapsed')
  if (savedCollapseState !== null) {
    isCollapse.value = savedCollapseState === 'true'
  }
  
  const info = getUserInfo()
  if (info) {
    userInfo.value = info
    // 根据角色加载对应菜单
    menuList.value = getMenuByRole(info.roleType)
    console.log('当前角色:', getRoleName(info.roleType))
    console.log('菜单列表:', menuList.value)
    
    // 异步加载完整用户信息
    await loadUserInfo()
  } else {
    ElMessage.error('获取用户信息失败，请重新登录')
    router.push('/login')
  }
  
  // 添加窗口大小变化监听
  window.addEventListener('resize', handleResize)
  handleResize()
})

// 窗口大小变化处理
const handleResize = () => {
  // 在小屏幕上自动折叠侧边栏
  if (window.innerWidth < 1024 && !isCollapse.value) {
    isCollapse.value = true
    localStorage.setItem('sidebar_collapsed', true)
  }
}

// 菜单选择
const handleMenuSelect = (path) => {
  router.push(path)
  // 在移动设备上选择菜单项后自动折叠侧边栏
  if (window.innerWidth < 768) {
    isCollapse.value = true
  }
}

// 下拉菜单命令处理
const handleCommand = (command) => {
  if (command === 'logout') {
    handleLogout()
  }
}

// 退出登录
const handleLogout = () => {
  ElMessageBox.confirm('确定要退出登录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    removeToken()
    localStorage.removeItem('sidebar_collapsed')
    ElMessage.success('已退出登录')
    router.push('/login')
  }).catch(() => {})
}

// 监听路由变化
watch(() => route.path, () => {
  // 路由变化时可以添加额外处理
})
</script>

<style scoped>
.layout-container {
  width: 100%;
  height: 100vh;
  overflow: hidden;
}

.main-container {
  width: 100%;
  height: 100%;
  transition: all 0.3s ease;
}

/* 左侧菜单栏 */
.sidebar {
  background: #304156;
  color: #fff;
  overflow-y: auto;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.1);
  transition: width 0.3s ease;
}

.logo-container {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #2b3a4a;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  padding: 0 16px;
}

.logo-container h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #fff;
  letter-spacing: 1px;
  transition: all 0.3s ease;
}

.logo-text-short {
  font-size: 20px;
  letter-spacing: 0;
}

.el-menu-vertical {
  border-right: none;
  background: #304156;
  height: calc(100% - 60px);
}

:deep(.el-menu-item) {
  height: 50px;
  line-height: 50px;
  color: rgba(255, 255, 255, 0.85);
  border-left: 3px solid transparent;
  font-size: 14px;
  padding-left: 20px !important;
  margin: 2px 0;
  transition: all 0.3s ease;
}

:deep(.el-menu-item:hover) {
  background: #293846 !important;
  border-left-color: #409EFF;
  color: #fff !important;
}

:deep(.el-menu-item.is-active) {
  background: #293846 !important;
  border-left-color: #409EFF;
  color: #fff !important;
}

:deep(.el-menu-item .el-icon) {
  font-size: 16px;
  margin-right: 10px;
}

/* 顶部导航栏 */
.main-header {
  background: #fff;
  border-bottom: 1px solid #eaeaea;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  height: 60px;
  padding: 0;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 100%;
  padding: 0 20px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.sidebar-toggle-btn {
  color: #606266;
  border-color: #dcdfe6;
  background-color: #fff;
  transition: all 0.3s ease;
}

.sidebar-toggle-btn:hover {
  color: #409EFF;
  border-color: #409EFF;
  background-color: #ecf5ff;
}

.breadcrumb h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.role-tag {
  font-size: 12px;
}

.username {
  font-size: 14px;
  color: #606266;
  max-width: 150px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

:deep(.el-dropdown-link) {
  display: flex;
  align-items: center;
  color: #606266;
  cursor: pointer;
  transition: color 0.3s ease;
}

:deep(.el-dropdown-link:hover) {
  color: #409EFF;
}

:deep(.el-dropdown-link .el-icon) {
  font-size: 16px;
}

:deep(.el-dropdown-link .el-icon--right) {
  font-size: 12px;
  margin-left: 4px;
}

/* 主内容区 */
.main-content {
  padding: 20px;
  background: #f5f7fa;
  overflow-y: auto;
  height: calc(100vh - 60px);
}

/* 过渡动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 响应式设计 */
@media screen and (max-width: 1024px) {
  .sidebar {
    width: 64px !important;
  }
  
  .logo-container h2:not(.logo-text-short) {
    display: none;
  }
  
  .header-content {
    padding: 0 16px;
  }
  
  .main-content {
    padding: 16px;
  }
}

@media screen and (max-width: 768px) {
  .main-header {
    height: 56px;
  }
  
  .header-content {
    padding: 0 12px;
  }
  
  .breadcrumb h3 {
    font-size: 14px;
  }
  
  .username {
    display: none;
  }
  
  .main-content {
    padding: 12px;
    height: calc(100vh - 56px);
  }
}

@media screen and (max-width: 480px) {
  .main-content {
    padding: 8px;
  }
  
  .role-tag {
    display: none;
  }
}
</style>
